package com.yu.mall.service;

import com.yu.mall.dto.address.AddressDTO;
import com.yu.mall.entity.Address;
import com.yu.mall.mapStruct.address.AddressDTOChange;
import com.yu.mall.mapStruct.address.AddressVOChange;
import com.yu.mall.mapper.AddressMapper;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.ResultVO;
import com.yu.mall.vo.address.AddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AddressService extends BaseService<Address> {

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    AddressDTOChange addressDTOChange;

    @Autowired
    AddressVOChange addressVOChange;

    public ResultVO add(AddressDTO addressDTO) {
        Address address = addressDTOChange.toBean(addressDTO);
        address.setId(null);
        address.setIsDelete("0");
        address.setCreateTime(new Date());
        address.setUpdateTime(new Date());
        //是默认地址
        if("1".equals(addressDTO.getIsDefault())){
            addressMapper.updateDefault(addressDTO.getOpenid());
        }
        addressMapper.insertSelective(address);
        return ResultUtils.success();
    }

    public ResultVO update(AddressDTO addressDTO) {
        Address address = addressDTOChange.toBean(addressDTO);
        address.setOpenid(addressDTO.getOpenid());
        address.setUpdateTime(new Date());
        address.setIsDelete("0");
        //是默认地址
        if("1".equals(addressDTO.getIsDefault())){
            addressMapper.updateDefault(addressDTO.getOpenid());
        }
        int i = addressMapper.updateByPrimaryKey(address);
        if(i <= 0){
            return ResultUtils.error("修改失败");
        }
        return ResultUtils.success();
    }

    public ResultVO<List<AddressVO>> list(String openid) {
        Example example = new Example(Address.class);
        example.orderBy("isDefault").desc();
        example.createCriteria().andEqualTo("openid",openid).andEqualTo("isDelete","0");
        List<Address> list = addressMapper.selectByExample(example);
        List<AddressVO> vos = addressVOChange.toVo(list);
        return ResultUtils.success(vos);
    }

    public ResultVO<AddressVO> getDefault(String openid) {
        Address address = new Address();
        address.setOpenid(openid);
        address.setIsDefault("1");
        address.setIsDelete("0");
        address = addressMapper.selectOne(address);
        AddressVO addressVO = addressVOChange.toVo(address);
        return ResultUtils.success(addressVO);
    }
}
